//
//  MemberViewCtrl.m
//  AccuroFit
//
//  Created by NCIT Developer on 3/11/16.
//  Copyright © 2016 Nci Technology Inc. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AppDelegate.h"
#import "MemberViewCtrl.h"
#import "EditUserView.h"

#import "N_GroupInfo.h"

#define _tabCellHgt 42
#define _Syn_OK "SynOk"

static NSString* _sMainBodyId;
static NSString* _sBodyId;
static NSInteger _nTableEditRow = -1;
static BOOL _bSignedUser =  NO;

//static char _szSyncDl[] = "DnldPrf";

//static uint16_t _nScalePort = 3000;
//static char _szScaleAddr[32] = "192.168.1.1";

@interface MemberViewCtrl ()

@end

@implementation MemberViewCtrl {
  UIImage* _imgTop;
  UIImageView* _ivTop;
  UIImage* _imgBottom;
  UIImageView* _ivBom;
  
  UIButton *_btnProf;
  UILabel* _lblInfo;
  UIButton* _btnReflash;
  UIActivityIndicatorView* _actIndicator;
  
  UIImageView* _ivFrofile;
  
  /*UIButton*   _btnHome;
  UIButton*   _btnReal;
  UIButton*   _btnBracelet;
  UIButton*   _btnBcaMeas;
  UIButton*   _btnBldPres;
  UIButton*   _btnHtRate;
  UIButton*   _btnGraph;
  UIButton*   _btnTable;
  //UIButton*   _btnProf;
  UIButton*   _btnGoals;
  UIButton*   _btnSet;*/
  
  UIPageControl* _pageIdx;
  
  //user data
  //double _BodyHgt;
  UITableView* _tabView;
  NSMutableArray* _userArray;
  
  //egofreshview
  BOOL _reloading;
  //EGORefreshTableHeaderView *_refreshHeaderView;
  
  //sync data and socket
  Boolean m_bResolved;
  NcitWiFiDev *_socketSvr;
  
  Boolean m_bStartSync;
  Boolean m_bUpToDate;
  NSUInteger m_nUpdCount;
  
  //edit user
  EditUserView* _editUserView;
  NSDateFormatter* _dtFmt;
  
  BOOL _bIpad;
}

- (void) _showAlert:(NSString *)title {
  [self stopUserActindicator];
  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message: NSLocalizedString(@"CheckWANConn", nil)
                                                     delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
  [alertView show];
  //[alertView release];
}

- (void)viewDidLoad {
  [super viewDidLoad];
    // Do any additional setup after loading the view.
  self.view.backgroundColor = [UIColor colorWithWhite:0.875 alpha:1.00];
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _dtFmt = pApp.dtFmt;
  //[pApp.managedObjectContext setStalenessInterval:0.0]; //强制性从磁盘装载
  
  //NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
  /*_sMainBodyId = [userSetting stringForKey:kBodyIdStr];;
  _sBodyId = [userSetting stringForKey:kBodyIdCur];
  if(_sBodyId == nil)
    _sBodyId = [userSetting stringForKey:kBodyIdStr];
  if(_sBodyId == nil)
    _sBodyId = @"-1";*/
  
  CGRect frame = [[UIScreen mainScreen] bounds];
  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  CGFloat yPos = (H <= 480)? 58: 62;
  _bIpad = H > 1000;
  [self addOtherCtrls:yPos scrWdt:W scrHgt:H];
  
  //image buttons, download
  UIImage* iBtn = [UIImage imageNamed:@"ic_cloud_dl.png"];
  _btnReflash = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnReflash.frame = CGRectMake(10, yPos+70, 28, 28);
  [_btnReflash setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnReflash addTarget:self action:@selector(actEvent:) forControlEvents:UIControlEventTouchUpInside];
  [_btnReflash setAdjustsImageWhenDisabled: YES];
  [self.view addSubview:_btnReflash];
  
  frame = CGRectMake(40, yPos+70, 250, 28);
  _lblInfo = [[UILabel alloc] initWithFrame:frame];
  _lblInfo.textAlignment = NSTextAlignmentCenter;// NSTextAlignmentRight;//UITextAlignmentRight;
  _lblInfo.text = NSLocalizedString(@"GrpList", nil) ;//@"Group List";//_sCurUserEmail;
  [self.view addSubview:_lblInfo];
  
  iBtn = [UIImage imageNamed:@"ic-addUser.png"];
  _btnProf = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnProf.frame = CGRectMake(W-35, yPos+70, 28, 28);
  [_btnProf setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnProf addTarget:self action:@selector(actEvent:) forControlEvents:UIControlEventTouchUpInside];
  [_btnProf setAdjustsImageWhenDisabled: YES];
  [self.view addSubview:_btnProf];
  
  _actIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(/*W-35*/10, yPos+70, 28, 28)];
  _actIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
  _actIndicator.hidesWhenStopped = YES;
  [self.view addSubview:_actIndicator];
  _actIndicator.hidden = YES;
  
  CGFloat fCtrlHgt = (H > 1000)? (H-245): (H-230);
  _tabView = [[UITableView alloc] initWithFrame:CGRectMake(2, yPos+130, W-4, fCtrlHgt)];
  _tabView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:0.9];
  //_tabView.backgroundColor = [UIColor lightGrayColor];
  _tabView.dataSource = self;
  _tabView.delegate = self;
  _tabView.rowHeight = _tabCellHgt;
  if(H > 1000)
    _tabView.rowHeight = _tabCellHgt * 1.5;
  [self.view addSubview:_tabView];
  
  //edit user
  _editUserView = [[EditUserView alloc] initWithFrame:CGRectMake(0, yPos+100, W, (W>500)?480:400)];
  _editUserView.backgroundColor = [UIColor colorWithWhite:0.80 alpha:1.0];
  //_loginPanel.hisetParentViewCtrldden = YES;
  //[_editUserView setParentViewCtrl:self];
  [self.view addSubview:_editUserView];
  
  //[appDelegate setPageIdxInfo:3 lastPage:3];
  [self loadSqliteData];
  [self setupSwipeGesture];
  
  //if(_sBodyId.intValue == -1) {
  if(![pApp isBodyLogged]) {
    _btnReflash.enabled = NO;
    _btnProf.enabled = NO;
    
    _lblInfo.text = NSLocalizedString(@"NoLoginTip", nil);
    _lblInfo.textColor = [UIColor redColor];
    _lblInfo.userInteractionEnabled = YES;
    
    //[_lblInfo addTarget:self action:@selector(actEvent:) forControlEvents:UIControlEventTouchUpInside];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLogin:)];
    [_lblInfo addGestureRecognizer:tapGesture];
  }
  
  //egofreshview
  /*if (_refreshHeaderView == nil) {
    eWgtViewController* rtViewCtrl = (eWgtViewController*)appDelegate.window.rootViewController;
    _refreshHeaderView = rtViewCtrl.refreshEgoView;
    
    _refreshHeaderView.delegate = self;
    [_tabView addSubview:_refreshHeaderView];
    
    [_refreshHeaderView refreshLastUpdatedDate];
  }*/
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) viewWillAppear:(BOOL)animated
{
  [self loadMemberUserInfo];
  //[self performSelectorOnMainThread:@selector(showSyncMembUsers) withObject:nil waitUntilDone:NO];
  _btnReflash.hidden = NO;
  _btnProf.hidden = NO;
}

- (void) viewWillDisappear:(BOOL)animated
{
  _tabView.dataSource = nil;
  _tabView.delegate = nil;
  //_refreshHeaderView.delegate = nil;
  
  [_ivTop removeFromSuperview];
  [_ivBom removeFromSuperview];
  
  /*[_btnHome removeFromSuperview];
  [_btnReal removeFromSuperview];
  [_btnGraph removeFromSuperview];
  [_btnTable removeFromSuperview];
  [_btnGoals removeFromSuperview];
  [_btnSet removeFromSuperview];*/
  
  [_btnProf removeFromSuperview];
  [_lblInfo removeFromSuperview];
  [_btnReflash removeFromSuperview];
  
  [_actIndicator removeFromSuperview];
  [_ivFrofile removeFromSuperview];
  
  [_pageIdx removeFromSuperview];
  [_editUserView viewDisappear];
  
  [super viewDidDisappear:animated];
}


-(void) loadMemberUserInfo
{
  [_userArray removeAllObjects];
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSMutableArray* pData = [NSMutableArray arrayWithArray:[pApp loadMemberUserInfo:0 grpId:pApp.m_nLoginBodyId]];
  if(pData == nil || pData.count == 0) {
    _userArray = nil;
    return;
  }
  
  _userArray = [NSMutableArray arrayWithArray: pData];
}

- (void) setupSwipeGesture
{
  //left swipe
  UISwipeGestureRecognizer * swipeGestureLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
  swipeGestureLeft.direction = UISwipeGestureRecognizerDirectionLeft;
  [self.view addGestureRecognizer:swipeGestureLeft];
  //[swipeGestureLeft release];
  //right swipe
  UISwipeGestureRecognizer * swipeGestureRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
  swipeGestureRight.direction = UISwipeGestureRecognizerDirectionRight;
  [self.view addGestureRecognizer:swipeGestureRight];
  //[swipeGestureRight release];
}

- (void)addOtherCtrls:(CGFloat) yPos scrWdt:(CGFloat) W scrHgt:(CGFloat)H
{
  _imgTop = [UIImage imageNamed:@"img-top.png"];
  UIImageView* iTopView = [[UIImageView alloc] initWithImage:_imgTop];
  iTopView.frame = CGRectMake(0, yPos, W, 66);
  [self.view addSubview:iTopView];
  _ivTop = iTopView;
  
  _imgBottom = [UIImage imageNamed:@"img-bottom.png"];
  UIImageView* iBtmView = [[UIImageView alloc] initWithImage:_imgBottom];
  iBtmView.frame = CGRectMake(0, H-128+yPos, W, 108);
  [self.view addSubview:iBtmView];
  _ivBom = iBtmView;
  
  UIImage* imgBkgd = [UIImage imageNamed:@"ic_profile.png"];
  _ivFrofile = [[UIImageView alloc] initWithImage:imgBkgd];
  _ivFrofile.frame = CGRectMake(40, yPos+100, 260, 25);
  [self.view addSubview:_ivFrofile];
}

- (void) loadSqliteData {
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //_userArray = [pApp loadSqliteGroupInfo:@"0" grpId:appDelegate.sBodyId];
}

- (void) runstopIndicator:(BOOL)bRun {
  if(bRun)
    [self performSelectorInBackground:@selector(startUserActindicator) withObject:nil];
  else
    [self performSelectorInBackground:@selector(stopUserActindicator) withObject:nil];
}

- (void) startUserActindicator
{
  _btnReflash.hidden = YES;
  _actIndicator.hidden = NO;
  [_actIndicator startAnimating];
}

- (void) stopUserActindicator
{
  //_btnReflash.hidden = NO;
  _actIndicator.hidden = YES;
  [_actIndicator stopAnimating];
}

/*-(void) startWiFiConn
{
  [self startUserActindicator];
}*/

- (void) tapLogin:(id)sender
{
  /*NSArray* arGesRec = [_lblInfo gestureRecognizers];
  if(arGesRec.count > 0)
    [_lblInfo removeGestureRecognizer:(UIGestureRecognizer*)arGesRec[arGesRec.count-1]];
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  ViewController* rtViewCtrl = (ViewController*)pApp.window.rootViewController;
  [pApp setPageIdxInfo:0 lastPage:6];
  [rtViewCtrl setMenuIdx:0];*/
}

- (void) actEvent:(id)sender {
  if(sender == _btnProf) {
    if([_actIndicator isAnimating])
      [self endSyncData];
    //add user
    if(_editUserView.isPopup) {
      [_editUserView hideUser];
    }
    else { //new one
      NSString* sBornDate = [AppDelegate isLanguageChines]?@"1970-01-01": @"01/01/1970";
      [_editUserView setUserInfo:@"" sex:1 chest:0.0 waist:0.0f wgt:@"" wun:1 hgt:@"" hun:1 born:sBornDate fitLvl:0 bodyId:0];
      [_editUserView popupUser];
    }
    _btnReflash.hidden = YES;
    _btnProf.hidden = YES;
  }
  else {
    if(_editUserView.isPopup)
      [_editUserView hideUser];
    [self startSyncData];
  }
}

- (void)handleSwipeGesture:(UIGestureRecognizer*)sender {
  /*AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *)sender direction];
  switch(direction) {
    case UISwipeGestureRecognizerDirectionLeft:
      appDelegate.nPageIdx++;
      break;
    case UISwipeGestureRecognizerDirectionRight:
      appDelegate.nPageIdx--;
      break;
    default:
      return;
  }
  if(appDelegate.nPageIdx < 0 || appDelegate.nPageIdx > 6) {
    [appDelegate setPageIdxInfo:2 lastPage:2];
    return;
  }
  
  bool bToRight = direction == UISwipeGestureRecognizerDirectionRight;
  
  CATransition* animation = [CATransition animation];
  [animation setDuration:0.4f];
  [animation setType:kCATransitionPush];//(bToRight? kCATransitionMoveIn: kCATransitionReveal)];
  [animation setSubtype:(bToRight? kCATransitionFromLeft: kCATransitionFromRight)];
  [[self.view.superview layer]addAnimation:animation forKey:@"switchView"];
  
  if(bToRight)
    [self popMenuItem:_btnTable];
  else {
    [self popMenuItem:_btnGoals];
  }*/
}

- (void) homeMenuItem:(id)sender
{
  [self dismissViewControllerAnimated:NO completion:nil];
  
  /*AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
   appDelegate.nPageIdx = 0;
   appDelegate.nLastPage = 0;
   UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
   eWgtViewController* vCtrlHome = [mainStory instantiateViewControllerWithIdentifier:@"mainPage"];
   [self presentViewController:vCtrlHome animated:YES completion:^ {
   //[vCtrlHome updateViewConstraints]; //restorationParent];
   //[self dismissViewControllerAnimated:NO completion:nil];
   }];*/
}

- (void) popMenuItem:(id)sender
{
  //_refreshHeaderView = nil;
  /*AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  ViewController* rtViewCtrl = (ViewController*)pApp.window.rootViewController;
  
  UIButton* btnSel = (UIButton*)sender;
  if(btnSel == _btnHome) {
    [appDelegate setPageIdxInfo:0 lastPage:88];
    [rtViewCtrl setMenuIdx:0];
  }
  else if(btnSel == _btnReal) {
    [appDelegate setPageIdxInfo:1 lastPage:8];
    [rtViewCtrl setMenuIdx:1];
  }
  else if(btnSel == _btnBracelet) {
    [appDelegate setPageIdxInfo:2 lastPage:8];
    [rtViewCtrl setMenuIdx:2];
  }
  else if(btnSel == _btnBcaMeas) {
    [appDelegate setPageIdxInfo:3 lastPage:8];
    [rtViewCtrl setMenuIdx:3];
  }
  else if(btnSel == _btnBldPres) {
    [appDelegate setPageIdxInfo:4 lastPage:8];
    [rtViewCtrl setMenuIdx:4];
  }
  else if(btnSel == _btnHtRate) {
    [appDelegate setPageIdxInfo:5 lastPage:8];
    [rtViewCtrl setMenuIdx:5];
  }
  else if(btnSel == _btnGraph) {
    [appDelegate setPageIdxInfo:6 lastPage:8];
    [rtViewCtrl setMenuIdx:6];
  }
  else if(btnSel == _btnTable) {
    [appDelegate setPageIdxInfo:7 lastPage:8];
    [rtViewCtrl setMenuIdx:7];
  }
  //else if(btnSel == _btnProf) {
  //[rtViewCtrl setMenuIdx:4];
  //}
  else if(btnSel == _btnGoals) {
    [appDelegate setPageIdxInfo:9 lastPage:8];
    [rtViewCtrl setMenuIdx:9];
  }
  else if(btnSel == _btnSet) {
    [appDelegate setPageIdxInfo:10 lastPage:8];
    [rtViewCtrl setMenuIdx:10];
  }*/
}

#pragma -
#pragma mark sysn data nad received data from server
- (void) syncUploadData {
  /*unsigned long i = _nIdxUpld;
   N_WgtData *nWgtData = (N_WgtData *)[m_nWgtArray objectAtIndex:i];
   int nMeasId = nWgtData.measId.intValue;
   //if(nMeasId == 144)
   //nMeasId = 0;
   if(nMeasId == 0) {
   NSString *iDate = [_dtFormat stringFromDate:[nWgtData scaDateTime]];
   char sUn[4];
   strcpy(sUn, (nWgtData.mWgtUnit.intValue == 1)? "kg": "lb");
   NSString *sMsg = [NSString stringWithFormat:@"1234 %s%d %@ %@ %@ %.3f %s %@", _szSyncUl, nMeasId,
   nWgtData.isnScale, _sCardNo, _sBodyId, nWgtData.mWgtData.floatValue, sUn, iDate];
   [_socketSvr syncDataOn:(char*)[sMsg UTF8String] Alert:NO];
   }
   else {
   //_nIdxUpld--;
   NSMutableString *sRtn = [[NSMutableString alloc] initWithCapacity:8];
   [sRtn setString:@Rcv_OK];
   [self recvedScaleData:sRtn];
   }*/
}

- (void) syncDownloadData {
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(![pApp isNetWorkConnAvailable]) {
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
  long nGrpId = pApp.m_nLoginBodyId;
  NSString* sUrl = [NSString stringWithFormat:@"Host/GetGroupUsers/%ld", nGrpId];
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"GET" url:sUrl data:nil];


  //NSUInteger nCount = 0, nIdx = 0;
  // 6.同步发送请求
  //dispatch_sync(dispatch_get_main_queue(), ^{
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  //NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if (data != nil) {
      //[self setMgrCotxNotification:pApp.managedObjectContext];
      NSError *e = nil;
      NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e]; //
      if(jsonArray == nil) {
        [self stopUserActindicator];
        AudioServicesPlaySystemSound(1112);
        return;
      }
      /*else if(jsonArray.count == 4) {
        AudioServicesPlaySystemSound(1112);
        return;
      }*/
    
    
      for(NSDictionary *item in jsonArray) {
        NSString* sSn = @"000000";
        NSString* sCardNo = [NSString stringWithFormat:@"%@", [item objectForKey:@"BodyTagId"]];
      
        NSString* sBodyId = [NSString stringWithFormat:@"%@", [item objectForKey:@"BodyId"]];
        NSString* sName = [NSString stringWithFormat:@"%@", [item objectForKey:@"Email"]];
        NSString* sBorn = [NSString stringWithFormat:@"%@", [item objectForKey:@"BodyBirthDay"]];
        NSString* sSex = [NSString stringWithFormat:@"%@", [item objectForKey:@"Gender"]];
      
        NSString* sWgt = [NSString stringWithFormat:@"%@", [item objectForKey:@"BodyWgt"]];
        NSString* sWun = [NSString stringWithFormat:@"%@", [item objectForKey:@"WgtUnit"]];
        NSString* sHgt = [NSString stringWithFormat:@"%@", [item objectForKey:@"BodyHgt"]];
        NSString* sHun = [NSString stringWithFormat:@"%@", [item objectForKey:@"HgtUnit"]];
      
        NSString* sChest = [NSString stringWithFormat:@"%@", [item objectForKey:@"ChestSize"]];
        NSString* sWaist = [NSString stringWithFormat:@"%@", [item objectForKey:@"WaistLine"]];
      
        NSString* sFitLvl = [NSString stringWithFormat:@"%@", [item objectForKey:@"FitLvl"]];
        
        //[NSOperationQueue mainQueue];
        //dispatch_sync(dispatch_get_main_queue(), ^{
      
        [pApp insertMembGroupInfo:nGrpId bodyId:sBodyId.integerValue sn:sSn card:sCardNo email:sName chest:sChest waist:sWaist sex:sSex age:sBorn
                              wgt:sWgt wun:sWun hgt:sHgt hun:sHun isAhtlet:sFitLvl];
        //});
      }
    
      //[self loadMemberUserInfo];
      //[_tabView reloadData];
      [self performSelectorOnMainThread:@selector(showSyncMembUsers) withObject:nil waitUntilDone:NO];
    }
  }];
  
  //});
}

-(void) showSyncMembUsers
{
  [self loadMemberUserInfo];
  [_tabView reloadData];

  [self stopUserActindicator];
  AudioServicesPlaySystemSound(1109);
}

-(void) refreshMembData
{
  [self performSelectorOnMainThread:@selector(showSyncMembUsers) withObject:nil waitUntilDone:NO];
}

- (void) showTopButs
{
  _btnReflash.hidden = NO;
  _btnProf.hidden = NO;  
}

/*- (void) setMgrCotxNotification:(NSManagedObjectContext*) moc
{
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  [nc addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:moc];
}

- (void)mergeChanges:(NSNotification *)notification {
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSManagedObjectContext *mainThreadMOC = pApp.managedObjectContext;
  
  //this tells the main thread moc to run on the main thread, and merge in the changes there
  [mainThreadMOC performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES];
}*/

- (void) startSyncData {
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [_userArray removeAllObjects];
  [pApp removeCoreData:@"N_GroupInfo"];
  [_tabView reloadData];
  NSInteger nBodyId = pApp.m_nLoginBodyId;
  
  //if(rng.location == NSNotFound || sCardNo == nil || [sCardNo compare:@""] == NSOrderedSame) {
  if(nBodyId <= 0) {
    [self _showAlert:NSLocalizedString(@"No sign in, please use the home page do that!", nil)];
    return;
  }
  [self performSelectorInBackground:@selector(startUserActindicator) withObject:nil];

  m_nUpdCount = 0;
  m_bUpToDate = NO;
  
  
  [self syncDownloadData];

  /*NSInteger nCount = _userArray.count;
  for(NSInteger i=0; i<nCount; i++ ) {
    N_GroupInfo* pBody = [_userArray objectAtIndex:i];
    [pApp refreshCoreDataItems:pBody];
  }
  
  [self performSelectorInBackground:@selector(stopUserActindicator) withObject:nil];
  if(nCount > 0)
    AudioServicesPlaySystemSound(1109);*/
}


- (void) endSyncData {
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [pApp CloseScaleHost];
  
  [self stopUserActindicator];
  [_tabView reloadData];
}

- (void) recvedScaleData: (NSMutableString *) sLine {
  //[self _showAlert:sLine];
  /*NSRange rng = [sLine rangeOfString:@_Syn_OK];
  Boolean bEnd = rng.location != NSNotFound;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString* sGrpId = [NSString stringWithFormat:@"%ld", pApp.m_nBodyId];
  
  NSArray* listItems = [sLine componentsSeparatedByString:@"\r\n"];
  NSUInteger n = [listItems count];
  if(n > 0) {
    if(m_bStartSync) {
      //[appDelegate removeCoreData];
      //[nWgtArray removeAllObjects];
      m_bStartSync = NO;
    }
    if([self savePrfDate: [listItems objectAtIndex:0] bodyId:sGrpId])
      m_nUpdCount++;
    NSUInteger nIdx = 1;
    while (nIdx < n) {
      if([self savePrfDate: [listItems objectAtIndex:nIdx] bodyId:sGrpId])
        m_nUpdCount++;
      nIdx++;
    }
  }
  
  if(m_bUpToDate)
    _lblInfo.text = [NSString stringWithFormat: @"Update User(s): %lu", (unsigned long)m_nUpdCount];
  else
    _lblInfo.text = @"No new date found";//@"No date found";
  
  if (bEnd) {
    //[self loadSqliteData];
    [pApp formGroupMemberData];
    
    if(n > 0)
      pApp.m_bDeleteData = NO;
    [self endSyncData];
    
    NSDate * dtNow = [NSDate date];
    NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
    [userSetting setObject:dtNow forKey:kLastPrfSyncDate];
    
    ViewController* rtViewCtrl = (ViewController*)pAPp.window.rootViewController;
    [rtViewCtrl showLoginInfo:nil];
  }*/
}

#pragma mark save data recv from server
-(Boolean) savePrfDate:(NSString*)sLine bodyId:(NSString*)sBodyId {
  Boolean bOK = NO;
  /*AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSArray *listItems = [sLine componentsSeparatedByString:@" "];
  NSUInteger n = [listItems count];
  if(n > 9) {
    NSString *sId = [listItems objectAtIndex:0];
    NSString* sSn = [listItems objectAtIndex:1];
    NSString *sCard = [listItems objectAtIndex:2];
    NSString *sEmail = [listItems objectAtIndex:3];
    //char* szEmail = [sEmail UTF8String];
    NSString *sSex = [listItems objectAtIndex:4];
    NSString *sWgt = [listItems objectAtIndex:5];
    NSString *sWun = [listItems objectAtIndex:6];
    NSString *sHgt = [listItems objectAtIndex:7];
    NSString *sHun = [listItems objectAtIndex:8];
    NSString *sBorn = [listItems objectAtIndex:9];
    NSString *sAth = [listItems objectAtIndex:10];
    
    sEmail = [sEmail stringByReplacingOccurrencesOfString:@"&" withString:@" "];
    
    if([sId isEqualToString:_sMainBodyId]) {
      NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
      NSString * sUserCardNo = [userSetting stringForKey:kCardNoStr];
      if(![sCard isEqualToString:sUserCardNo]) {
        [userSetting setObject:sCard forKey:kCardNoStr];
      }
    }
    
    N_GroupInfo *nGrpData = [pApp insertGroupInfo:sBodyId bodyId:sId sn:sSn card:sCard email:sEmail sex:sSex age:sBorn wgt:sWgt wun:sWun hgt:sHgt hun:sHun isAhtlet:sAth];
    if(nGrpData) {
      [_userArray insertObject:nGrpData atIndex:0];
      m_bUpToDate = YES;
      bOK = YES;
    }
  }*/
  
  return bOK;
}

- (void) connFailed
{
  //self.navigationItem.title = @"No way to conn.";
  [self endSyncData];
  //[self _showAlert: @"Contact host failed, Maybe need close WiFi conn-with scale"];
}

#pragma -
#pragma -table view delegate
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
  // Return YES if you want the specified item to be editable.
  return indexPath.row == _nTableEditRow;
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
  NSInteger nCount = _userArray.count;
  return nCount;
}

- (NSString *)tableView:(UITableView *)table titleForHeaderInSection:(NSInteger)section {
  //WiFiScaleAppDelegate *appDelegate = (WiFiScaleAppDelegate *)[[UIApplication sharedApplication] delegate];
  //if(!appDelegate.m_bDeleteData && self.view == self.tabView)
  return [NSString stringWithFormat:@" - %d items", (int)[_userArray count]];
}

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  if(_userArray == nil || _userArray.count == 0)
    return nil;
  
  static NSString *kCellIdentifier = @"GrdCell";
  UITableViewCell *cell = [_tabView dequeueReusableCellWithIdentifier:kCellIdentifier];
  if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier];
    //cell.textLabel.font = [UIFont systemFontOfSize:16];
  }
  
  //user data
  N_GroupInfo *nGrp = (N_GroupInfo *)[_userArray objectAtIndex:indexPath.row];
  //NSString* sCarNo =  nGrp.cardNo;
  
  NSString* sSexImg = nil;
  short nSex = [nGrp.bodySex shortValue];
  if(nSex == 0)
    sSexImg = @"ic_female.png";
  else if(nSex == 1)
    sSexImg = @"ic_male.png";
  else
    sSexImg = @"ic_gmale.png";
  cell.imageView.image = [UIImage imageNamed:sSexImg];
  cell.imageView.userInteractionEnabled = YES;
  cell.imageView.tag = indexPath.row;
  UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ugdUserCard:)];
  tapped.numberOfTapsRequired = 1;
  [cell.imageView addGestureRecognizer:tapped];
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
  if([AppDelegate isLanguageChines])
    [pApp.dtFmt setDateFormat:@"yyyy-MM"];
  else
    [pApp.dtFmt setDateFormat:@"MM/yyyy"];
  NSString* sBornDate = [pApp.dtFmt stringFromDate:nGrp.bodyAge];

  
  cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:((_bIpad)?20.0:13.0)];
  if(nGrp.wgtUnit.shortValue != 1) {
        if(nGrp.hgtUnit.shortValue != 1) {
      float fHgt = [nGrp.bodyHgt floatValue];
      int nHgtFt =  (int)fHgt;
      float fHgtIn =  (fHgt - nHgtFt) * 12;
      cell.textLabel.text = [NSString stringWithFormat: @"%@  %.1f lb %d ft %.0f in  %@", nGrp.bodyEmail, [nGrp.bodyWgt floatValue], nHgtFt, fHgtIn, sBornDate];
    }
    else {
      cell.textLabel.text = [NSString stringWithFormat: @"%@  %.1f lb %.2f m  %@", nGrp.bodyEmail, [nGrp.bodyWgt floatValue], [nGrp.bodyHgt floatValue], sBornDate];
    }
  }
  else {
    if(nGrp.hgtUnit.shortValue != 1) {
      float fHgt = [nGrp.bodyHgt floatValue];
      int nHgtFt =  (int)fHgt;
      float fHgtIn =  (fHgt - nHgtFt) * 12;
      cell.textLabel.text = [NSString stringWithFormat: @"%@  %.1f kg %d ft %.0f in  %@", nGrp.bodyEmail, [nGrp.bodyWgt floatValue], nHgtFt, fHgtIn, sBornDate];
    }
    else {
      cell.textLabel.text = [NSString stringWithFormat: @"%@  %.1f kg %.2f m  %@", nGrp.bodyEmail, [nGrp.bodyWgt floatValue], [nGrp.bodyHgt floatValue], sBornDate];
    }
  }
  
  
  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//UITableViewCellAccessoryCheckmark;
  
  //add swipe to remove and cancel
  cell.tag = indexPath.row;
  UISwipeGestureRecognizer* swipeRecRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeDel:)];
  [swipeRecRight setDirection:UISwipeGestureRecognizerDirectionLeft+UISwipeGestureRecognizerDirectionRight];
  [cell addGestureRecognizer:swipeRecRight];
  
  [pApp.dtFmt setDateFormat:sInitDtFmt];
  return cell;
}

- (void) ugdUserCard:(id)sender
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
  N_GroupInfo *nGrp = (N_GroupInfo *)[_userArray objectAtIndex:gesture.view.tag];
  NSInteger nBodyId = [nGrp.bodyId integerValue];
  
  //_lblInfo.text = [NSString stringWithFormat:@"Upd User Card: %ld", nBodyId];
  if(_editUserView.isPopup) {
    [_editUserView hideUser];
  }
  else {
    _bSignedUser = pApp.m_nLoginBodyId == nBodyId;
    //[self performSelectorInBackground:@selector(startWiFiConn) withObject:nil];
    [_editUserView ugdUserCardNo:nBodyId sex:[nGrp.bodySex shortValue] name:nGrp.bodyEmail sn:nGrp.scaleNo card:nGrp.cardNo];
    [_editUserView popupUser];
  }
  
  _btnReflash.hidden = YES;
  _btnProf.hidden = YES;
}

- (void) handleSwipeDel:(id)sender
{
  UISwipeGestureRecognizer *gesture = (UISwipeGestureRecognizer *) sender;
  //BOOL bDel = gesture.direction == UISwipeGestureRecognizerDirectionRight;
  //_nTableEditRow = bDel? gesture.view.tag: -1;
  if(_nTableEditRow >= 0)
    _nTableEditRow = -1;
  else
    _nTableEditRow = gesture.view.tag;
  [_tabView setEditing:_nTableEditRow>=0 animated:YES];
  
  //N_GroupInfo *nGrp = (N_GroupInfo *)[_userArray objectAtIndex:gesture.view.tag];
  //long nBodyId = [nGrp.bodyId integerValue];
  //_lblInfo.text = [NSString stringWithFormat:@"swipe delete: %ld", gesture.view.tag];
  //[_tabView setEditing:YES animated:YES];
}

- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath
{
  //NSString* sMsg = [NSString stringWithFormat:@"Click: %i", (int)indexPath.row];
  //UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Touch:" message:sMsg delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
  //[alertView show];
  if(_editUserView.isPopup) {
    [_editUserView hideUser];
  }
  else {
    N_GroupInfo *nGrp = (N_GroupInfo *)[_userArray objectAtIndex:indexPath.row];
    
    //[self performSelectorInBackground:@selector(startUserActindicator) withObject:nil];
    NSString* sWgt = [NSString stringWithFormat:@"%.1f", [nGrp.bodyWgt floatValue]];
    short nWun = [nGrp.wgtUnit shortValue] - 1;
    NSString* sHgt =[NSString stringWithFormat:@"%.2f", [nGrp.bodyHgt floatValue]];
    short nHun = [nGrp.hgtUnit shortValue] - 1;
    
    float fChest = 0, fWaist = 0;
    if(nGrp.fChest)
      fChest = nGrp.fChest.floatValue;
    if(nGrp.fWaist)
      fWaist = nGrp.fWaist.floatValue;
    
    NSString* sBorn = [AppDelegate isLanguageChines]? @"1900-01-01": @"01/01/1900";
    if(nGrp.bodyAge) {
      NSDateFormatter* dtFmt = _dtFmt;
      NSString* sInitDtFmt = _dtFmt.dateFormat;
      if([AppDelegate isLanguageChines])
        dtFmt.dateFormat = @"yyyy-MM-dd";
      else
        dtFmt.dateFormat = @"MM/dd/yyyy";
      sBorn = [dtFmt stringFromDate:nGrp.bodyAge];
      [_dtFmt setDateFormat:sInitDtFmt];
    }
    
    short nAct = 0;
    if(nGrp.athleteLvl)
      nAct = nGrp.athleteLvl.shortValue;
    long nBodyId = [nGrp.bodyId integerValue];
    
    _btnReflash.hidden = YES;
    _btnProf.hidden = YES;
    [_editUserView setUserInfo:nGrp.bodyEmail sex:[nGrp.bodySex shortValue]  chest:fChest waist:fWaist wgt:sWgt wun:nWun hgt:sHgt hun:nHun born:sBorn fitLvl:nAct bodyId:nBodyId];
    [_editUserView popupUser];
  }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
  //self.lineCtrler.hRate = [self.nWgtArray objectAtIndex:indexPath.row];
  //[self.navigationController pushViewController:self.lineCtrler animated:YES];
  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Touch:", nil) message:NSLocalizedString(@"Test click out row", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
  [alertView show];
  //[alertView release];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
  // Detemine if it's in editing mode
  if (_tabView.editing) {
    return UITableViewCellEditingStyleDelete;
  }
  
  return UITableViewCellEditingStyleNone;
}

/*-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if(indexPath.row == 0) {
 return  UITableViewCellEditingStyleInsert;
 }
 else {
 return UITableViewCellEditingStyleDelete;
 }
 }*/

/*- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
 //这里写你手指横向滑动需要处理的事件
 _lblInfo.text = @"swiape one";
 return nil;
 }*/

- (void)tableView:(UITableView *)tabView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Ensure that if the user is editing a name field then the change is committed before deleting a row -- this ensures that changes are made to the correct event object.
    [_tabView endEditing:YES];
    
    //NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
    NSString* sLogBodyId = [NSString stringWithFormat:@"%ld", (long)pApp.m_nLoginBodyId];//[userSetting stringForKey:kBodyIdStr];
    N_GroupInfo *nGrp = (N_GroupInfo *)[_userArray objectAtIndex:indexPath.row];
    if( nGrp.bodyId.integerValue == sLogBodyId.integerValue) {
      _nTableEditRow = -1;
      [_tabView reloadData];
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"NoWayDel", nil) message: NSLocalizedString(@"NoDelMsg", nil)
                                                         delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
      [alertView show];
      return;
    }
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext* managedObjectContext = appDelegate.managedObjectContext;
    
    // Delete the managed object at the given index path.
    NSManagedObject *rcdToDelete = [_userArray objectAtIndex:indexPath.row];
    [managedObjectContext deleteObject:rcdToDelete];
    
    // Update the array and table view.
    [_userArray removeObjectAtIndex:indexPath.row];
    [_tabView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    // Commit the change.
    NSError *error;
    if (![managedObjectContext save:&error]) {
      // Handle the error.
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      exit(-1);  // Fail
    }
    else {
      [_tabView reloadData];
    }
    _nTableEditRow = -1;
    //[appDelegate formGroupMemberData];
    //[_tabView reloadData];
  }
  
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

/*- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
  [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

- (void)doneLoadingTableViewData {
  //  model should call this when its done loading
  _reloading = NO;
  [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_tabView];
  
}*/


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
/*- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
  _reloading = YES;
  [self startSyncData];
  [_tabView reloadData];
  [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.0];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
  [_refreshHeaderView refreshLastUpdatedDate];
  return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
  //return [NSDate date]; // should return date data source was last changed
  NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
  return (NSDate*)[userSetting objectForKey:kLastPrfSyncDate];
}*/

- (void) updateUserInfo:(BOOL)bUpd bodyId:(NSInteger)nId newTag:(NSString*)sNewTag
{
  /*[self loadSqliteData];
  [_tabView reloadData];
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [pApp formGroupMemberData];
  ∫ViewController* rtViewCtrl = (ViewController*)appDelegate.window.rootViewController;
  [rtViewCtrl showLoginInfo:nil];
  
  
  if(bUpd) {
    NSString* sId = [NSString stringWithFormat:@"%u", (int)nId];
    if([sId isEqualToString:_sMainBodyId]) {
      NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
      NSString * sUserCardNo = pApp.m_bodyInfo.m_sTagId;//[userSetting stringForKey:kCardNoStr];
      if(![sNewTag isEqualToString:sUserCardNo]) {
        [userSetting setObject:sNewTag forKey:kCardNoStr];
      }
    }
  }*/
  
  _lblInfo.text = NSLocalizedString(@"Update the user", nil);
}

- (void) updateUserInfoHgt:(NSString*) sHgt
{
  [self updateUserInfo: NO bodyId:0 newTag:nil];
}

@end
